package model

import (
	"context"
	"fmt"
	"strings"

	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ PodcastsModel = (*customPodcastsModel)(nil)

type (
	// PodcastsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customPodcastsModel.
	PodcastsModel interface {
		podcastsModel
		withSession(session sqlx.Session) PodcastsModel
		FindPageList(ctx context.Context, page, pageSize int64, keyword string) ([]*Podcasts, int64, error)
	}

	customPodcastsModel struct {
		*defaultPodcastsModel
	}
)

// NewPodcastsModel returns a model for the database table.
func NewPodcastsModel(conn sqlx.SqlConn) PodcastsModel {
	return &customPodcastsModel{
		defaultPodcastsModel: newPodcastsModel(conn),
	}
}

func (m *customPodcastsModel) withSession(session sqlx.Session) PodcastsModel {
	return NewPodcastsModel(sqlx.NewSqlConnFromSession(session))
}

// FindPageList 分页查询播客列表
func (m *customPodcastsModel) FindPageList(ctx context.Context, page, pageSize int64, keyword string) ([]*Podcasts, int64, error) {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	// 构建查询条件
	whereBuilder := strings.Builder{}
	whereBuilder.WriteString("1=1")
	args := make([]interface{}, 0)

	// 如果有关键词，添加模糊查询条件
	if len(keyword) > 0 {
		whereBuilder.WriteString(" AND (title LIKE ? OR content LIKE ? OR tags LIKE ?)")
		likeKeyword := "%" + keyword + "%"
		args = append(args, likeKeyword, likeKeyword, likeKeyword)
	}

	// 查询总数
	countQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE %s", m.table, whereBuilder.String())
	var count int64
	err := m.conn.QueryRowCtx(ctx, &count, countQuery, args...)
	if err != nil {
		return nil, 0, err
	}

	// 查询数据
	query := fmt.Sprintf("SELECT %s FROM %s WHERE %s ORDER BY id DESC LIMIT ?, ?", podcastsRows, m.table, whereBuilder.String())
	args = append(args, offset, pageSize)
	var resp []*Podcasts
	err = m.conn.QueryRowsCtx(ctx, &resp, query, args...)
	if err != nil {
		return nil, 0, err
	}

	return resp, count, nil
}
